import React from 'react';
import {
  Dialog as MuiDialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
} from '@mui/material';
import { useAppSelector, useAppDispatch } from '../../redux/hooks';
import { closeConfirmationDialog, pythonCall } from '../../redux/slices/generalSlice';
import { PYTHON_CALL, LOAD_TUTORIAL } from '../../constants';

const ConfirmationDialog: React.FC = () => {
  const dispatch = useAppDispatch();
  const {
    confirmationDialogOpen,
    confirmationDialogTitle,
    confirmationDialogMessage,
    confirmationDialogOnConfirm,
  } = useAppSelector((state) => state.general);

  const handleClose = (): void => {
    dispatch(closeConfirmationDialog());
  };

  const handleConfirmation = (): void => {
    if (confirmationDialogOnConfirm && confirmationDialogOnConfirm.type) {
      if (confirmationDialogOnConfirm.type === PYTHON_CALL) {
        dispatch(
          pythonCall(
            confirmationDialogOnConfirm.cmd,
            confirmationDialogOnConfirm.args,
          ),
        );
      } else if (confirmationDialogOnConfirm.type === LOAD_TUTORIAL) {
        if (confirmationDialogOnConfirm.payload !== undefined) {
          dispatch(
            confirmationDialogOnConfirm.action(confirmationDialogOnConfirm.payload),
          );
        } else {
          dispatch(confirmationDialogOnConfirm.action);
        }
      }
    }
    handleClose();
  };

  return (
    <MuiDialog fullWidth maxWidth="sm" open={confirmationDialogOpen} onClose={handleClose}>
      <DialogTitle>{confirmationDialogTitle}</DialogTitle>
      <DialogContent sx={{ color: 'text.primary' }}>
        {confirmationDialogMessage}
      </DialogContent>
      <DialogActions>
        {confirmationDialogOnConfirm && (
          <Button onClick={handleClose} sx={{ mr: 1.25 }} key="CANCEL">
            CANCEL
          </Button>
        )}
        <Button
          color="primary"
          variant="contained"
          onClick={handleConfirmation}
          key="CONFIRM"
        >
          CONFIRM
        </Button>
      </DialogActions>
    </MuiDialog>
  );
};

export default ConfirmationDialog;

